package com.tianji.promotion.lock.strategy;

import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.promotion.lock.MyLock;
import org.redisson.api.RLock;

public enum LockStrategyEnum {
    SKIP_FAST(){
        @Override
        public boolean lock(RLock lock, MyLock myLock) throws Exception{
            return lock.tryLock(0, myLock.leaseTime(), myLock.timeUnit());
        }
    },
    FAIL_FAST(){
        @Override
        public boolean lock(RLock lock,MyLock myLock) throws Exception{
            boolean locked = lock.tryLock(0, myLock.leaseTime(), myLock.timeUnit());
            if(!locked){
                throw new BizIllegalException("获取锁失败");
            }
            return locked;
        }
    },
    KEEP_TRYING(){
        @Override
        public boolean lock(RLock lock,MyLock myLock)throws Exception {
            lock.lock();
            return true;
        }
    },
    SKIP_AFTER_TIMEOUT(){
        @Override
        public boolean lock(RLock lock,MyLock myLock) throws Exception{
            return lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.timeUnit());
        }
    },
    FAIL_AFTER_TIMEOUT(){
        @Override
        public boolean lock(RLock lock,MyLock myLock)throws Exception {
            boolean locked = lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.timeUnit());
            if(!locked){
                throw new BizIllegalException("获取锁失败");
            }
            return locked;
        }
    };

    public abstract boolean lock(RLock lock, MyLock myLock)throws Exception;

    public void unlock(RLock lock){
        lock.unlock();
    }
}
